<?php

namespace Boosen\Admin\Contents\Models;

use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
	use ModelTree, AdminBuilder;
    protected $table = 'boosen_categories';
    

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->setTitleColumn('name');
    }
    
    public function getItemsTree($pid)
    {
        $items = (new static())::where('parent_id', $pid)->orderBy('order', 'asc')->get()->toArray();


        return $this->buildChildren($items, $pid);
    }


    private function buildChildren($nodes = [], $pid = 0)
    {
        $branch = [];

        if (empty($nodes)) {
            return $nodes;
        }


        foreach ($nodes as $node) {
            if ($node['parent_id'] == $pid) {
                $children = $this->buildNestedArray($nodes, $node['id']);

                if ($children) {
                    $node['children'] = $children;
                }

                $branch[] = $node;
            }
        }

        return $branch;
    }
}
